# -*- python -*-
# ex: set syntax=python:

from buildbot.plugins import *

manifest_url = "git://github.com/CyanogenMod/android.git"
manifest_branch = "froyo"

slaves = ["slave%02d"%(i) for i in range(1, 2)]

repotarball = "/local/android/cyanogen/cyanogen_bootstrap.tgz"

gerrit_server = "review.cyanogenmod.com"
gerrit_user = "yourid"

build_branches = []
# for i in "passion inc hero heroc sholes dream_sapphire bravo bravoc espresso
# supersonic liberty vibrant legend vision".split(" "):
for i in "passion hero dream_sapphire".split(" "):
    build_branches.append([i, "default.xml", "froyo"])

# This is the dictionary that the buildmaster pays attention to. We also use
# a shorter alias to save typing.
c = BuildmasterConfig = {}

## DB URL

# This specifies what database buildbot uses to store change and scheduler
# state
c['db_url'] = "sqlite:///state.sqlite"

## BUILDSLAVES

c['slaves'] = [buildslave.BuildSlave(i, i + "pw", max_builds=1) for i in slaves]
c['slavePortnum'] = 9989

## CHANGESOURCES

c['change_source'] = changes.GerritChangeSource(gerrit_server, gerrit_user)


## SCHEDULERS

## configure the Schedulers
buildernames = ["%s_%s" % (board, manifest)
                for board, manifest, gerrit_branch in build_branches]

c['schedulers'] = []

c['schedulers'].append(
    schedulers.SingleBranchScheduler(name="all",
                                     branch=None,
                                     treeStableTimer=2 * 60,
                                     builderNames=buildernames))

branches = {}
for board, manifest, gerrit_branch in build_branches:
    if not gerrit_branch in branches:
        branches[gerrit_branch] = []
    branches[gerrit_branch].append("%s_%s" % (board, manifest))

for branch in branches.keys():
    print branch, branches[branch]
    c['schedulers'].append(
        schedulers.SingleBranchScheduler(name=branch,
                                         branch=branch,
                                         treeStableTimer=None,
                                         builderNames=branches[branch]))

## BUILDERS

proprietary_url = "http://where.to.find.com/proprietaries/%(device)s.tgz"
getOutputDir = Interpolate("/var/www/builds/build-%(prop:buildername)s-%(prop:changenumber)s")
getWebDir = Interpolate("http://buildmaster.mysite.com/builds/build-%(prop:buildername)s-%(prop:changenumber)s")

builders = []
for board, manifest_file, gerrit_branch in build_branches:
    f1 = util.BuildFactory()
    f1.workdir = "system"
    f1.addStep(steps.Repo(manifest_url=manifest_url,
                          manifest_branch=manifest_branch,
                          manifest_file=manifest_file,
                          tarball=repotarball))
    f1.addStep(steps.Compile(name="clobber old output", command="rm -rf out"))
    f1.addStep(steps.Compile(name="download proprietaries",
                             command="curl \""+proprietary_url+"\" > props.tgz;" % ({'device': board}) +
                                     "tar zxvf props.tgz;" +
                                     "rm props.tgz;"))
    f1.addStep(steps.Compile(name="get rommanager",
                             command="./vendor/cyanogen/get-rommanager"))

    buildcommand = """
             set -e
             export LANG=C
             . build/envsetup.sh
             lunch cyanogen_%s-eng
             make -j4
             make bacon -j4
             repo manifest -o out/target/product/%s/manifest.xml
             """ % (board, board)
    f1.addStep(steps.Compile(name="compile everything",
                             command=["/bin/bash", "-c", buildcommand]))
        # todo should upload result of compilation somewhere else

    builddir = "%s_%s" % (board, manifest_file)
    b1 = util.BuilderConfig(name=builddir, slavenames=slaves,
                            builddir=builddir, factory=f1)
    builders.append(b1)

c['builders'] = builders

## STATUS TARGETS

# 'status' is a list of Status Targets. The results of each build will be
# pushed to these targets. buildbot/status/*.py has a variety to choose from,
# including web pages, email senders, and IRC bots.
c['status'] = []

# The code below is valid for 0.8.x versions, and is not valid for 0.9+
if 0:
    authz_cfg = util.Authz(
        # change any of these to True to enable; see the manual for more
        # options
        gracefulShutdown=True,
        forceBuild=True,
        forceAllBuilds=True,
        pingBuilder=True,
        stopBuild=True,
        stopAllBuilds=True,
        cancelPendingBuild=True,
    )

    c['status'].append(html.WebStatus(http_port=8010, authz=authz_cfg))

def gerritMessageCB(buildername, build, results):
    sep = "-------------------------------\n"
    message = "buildbot finished compiling your patchset\n"
    message += sep
    message += "on configuration %s\n"%(buildername)
    message += sep
    message += "the result is %s\n"%(Results[results])
    message += sep
    message += "more details %s/builders/%s/builds/%d\n" % (c['buildbotURL'], buildername, build.getNumber())
    return dict(message=message)

c['status'].append(status.GerritStatusPush(gerrit_server, gerrit_user,
                                           gerritMessageCB))

## PROJECT IDENTITY

# the 'title' string will appear at the top of this buildbot
# installation's html.WebStatus home page (linked to the 'titleURL')
# and is embedded in the title of the waterfall HTML page.

c['title'] = "froyo"
c['titleURL'] = "http://review.android.com"

# the 'buildbotURL' string should point to the location where the buildbot's
# internal web server (usually the html.WebStatus page) is visible. This
# typically uses the port number set in the Waterfall 'status' entry, but
# with an externally-visible host name which the buildbot cannot figure out
# without some help.

c['buildbotURL'] = "http://buildbot.cyanogenmod.com"
